package com.assessment.service.impl;

import com.assessment.service.UploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import static com.assessment.utils.Constant.CODE_ERROR;
import static com.assessment.utils.Constant.CODE_SUCCESS;


@Service
@Transactional
public class UploadServiceImpl implements UploadService {

    private static final Logger log = LoggerFactory.getLogger(UploadServiceImpl.class);
    @Value("${file.base.path}")
    private String BASE_PATH;
    @Override
    public Map<String, Object> uploadFile(MultipartFile file, String filePath){
        Map<String, Object> map = new HashMap<>();// 初始化返回信息
        map.put("path","");
        map.put("code", CODE_ERROR);
        if (file.isEmpty()) {//判断文件是否为空
            map.put("msg", "上传失败!文件内容为空，请检查上传的文件");
            return map;
        }
        String newFileName = System.currentTimeMillis() +"-"+ file.getOriginalFilename();// 时间戳 + 文件名
        String pathUrl = BASE_PATH+"/"+ filePath+"/"+ newFileName;// 文件在服务器保存的路径
        String retUrl =  "admin/download/"+filePath +"/"+ newFileName;// 返回文件保存路径
        System.out.println(retUrl);
        File dest = new File(pathUrl);
        if (dest.exists()){
            map.put("msg", "上传失败!文件重复，请重新上传");
            return map;
        }
        if (!dest.getParentFile().exists()) {//如果文件夹不存在就新建一个文件夹
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            map.put("msg", "文件上传成功！");
            map.put("path",retUrl);
            map.put("code", CODE_SUCCESS);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg", "文件上传失败！请重新上传");
            map.put("code", CODE_ERROR);
            return map;
        }
    }
}
